package cn.itcast.goods.user.web.servlet;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cn.itcast.goods.user.domain.User;
import cn.itcast.goods.user.service.UserService;
import cn.itcast.goods.user.service.exception.UserException;
import cn.mytools.commons.CommonUtils;
import cn.mytools.servlet.BaseServlet;

/**
 * 用户模块控制层
 * 
 * @author HL
 *
 */
public class UserServlet extends BaseServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = 8171602050918999229L;
	private UserService userService = new UserService();

	/**
	 * 用户注册
	 * 
	 * @param req
	 * @param resp
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	public String regist(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		User formUser = CommonUtils.toBean(req.getParameterMap(), User.class);

		Map<String, String> errors = validateRegist(formUser, req.getSession());
		if (errors.size() > 0) {
			req.setAttribute("errors", errors);
			req.setAttribute("form", formUser);
			return "f:/jsps/user/regist.jsp";
		}

		userService.regist(formUser);
		String mailAddres = "mail." + formUser.getEmail().substring(formUser.getEmail().indexOf("@") + 1);
		req.setAttribute("mailAddress", mailAddres);
		req.setAttribute("code", "success");
		req.setAttribute("msg", "注册成功，请马上到邮箱激活");

		return "f:/jsps/msg.jsp";
	}

	/**
	 * 用户登陆
	 * 
	 * @param req
	 * @param resp
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	public String login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		User formUser = CommonUtils.toBean(req.getParameterMap(), User.class);

		// 校验表单数据
		Map<String, String> errors = validateLogin(formUser, req.getSession());
		if (errors.size() > 0) {
			req.setAttribute("errors", errors);
			req.setAttribute("form", formUser);
			return "f:/jsps/user/login.jsp";
		}

		User user = userService.login(formUser);

		if (user != null) { // 用户存在
			if (user.getStatus() == 1) { // 已经激活
				String loginname = user.getLoginname();
				req.getSession().setAttribute("sessionUser", user); // 向session中保存user
				loginname = URLEncoder.encode(loginname, "utf-8");// 设置编码
				Cookie cookie = new Cookie("loginname", loginname);
				cookie.setMaxAge(60 * 60 * 24); // cookie 保存24小时
				resp.addCookie(cookie);
				return "r:/index.jsp"; // 重定向到主页
			} else { // 用户没有激活
				req.setAttribute("msg", "你还没有激活！");
				req.setAttribute("form", formUser);
				return "f:/jsps/user/login.jsp";
			}
		} else {// 用户不存在
			req.setAttribute("msg", "用户名或密码错误！");
			req.setAttribute("form", formUser);
			return "f:/jsps/user/login.jsp";
		}
	}

	public String updatePwd(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		User user = (User) req.getSession().getAttribute("sessionUser");
		if (user == null) {
			req.setAttribute("code", "error");
			req.setAttribute("msg", "您还没有登录，不能访问本资源");
			return "f:/jsps/msg.jsp";
		} else {
			return "f:/jsps/user/pwd.jsp";
		}
	}

	/**
	 * 修改密码
	 * 
	 * @param req
	 * @param resp
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	public String updatePassword(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		User formUser = CommonUtils.toBean(req.getParameterMap(), User.class);

		// 校验表单数据
		Map<String, String> errors = validateUpdatePassword(formUser, req.getSession());
		if (errors.size() > 0) {
			req.setAttribute("errors", errors);
			req.setAttribute("form", formUser);
			return "f:/jsps/user/pwd.jsp";
		}

		User user = (User) req.getSession().getAttribute("sessionUser");
		if (user == null) {
			req.setAttribute("msg", "您还没有登陆");
			return "f:/jsps/user/login.jsp";
		}

		String loginname = user.getLoginname();
		formUser.setLoginname(loginname);

		try {
			userService.updatePassword(formUser);
		} catch (UserException e) {
			req.setAttribute("form", formUser);
			req.setAttribute("msg", e.getMessage());
			return "f:/jsps/user/pwd.jsp";
		}

		req.setAttribute("code", "success");
		req.setAttribute("msg", "修改密码成功！");
		return "f:/jsps/msg.jsp";
	}

	/**
	 * 退出功能
	 * 
	 * @param req
	 * @param resp
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	public String quit(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.getSession().invalidate();
		return "r:/jsps/user/login.jsp";
	}

	/**
	 * 注册表单校验
	 * 
	 * @param formUser
	 * @param session
	 * @return
	 */
	private Map<String, String> validateRegist(User formUser, HttpSession session) {
		Map<String, String> errors = new HashMap<String, String>();

		// 用户名校验
		String loginname = formUser.getLoginname();
		if (loginname == null || loginname.trim().isEmpty()) {
			errors.put("loginname", "用户名不能为空！");
		} else if (loginname.length() < 3 || loginname.length() > 20) {
			errors.put("loginname", "用户名长度必须在3-20之间！");
		} else if (!userService.ajaxValidateLoginname(loginname)) {
			errors.put("loginname", "用户名已经被注册！");
		}

		// 密码校验
		String loginpass = formUser.getLoginpass();
		if (loginpass == null || loginpass.trim().isEmpty()) {
			errors.put("loginpass", "密码不能为空！");
		} else if (loginpass.length() < 3 || loginpass.length() > 20) {
			errors.put("loginpass", "密码长度必须在3-20之间！");
		}

		// 确认密码校验
		String reloginpass = formUser.getReloginpass();
		if (reloginpass == null || reloginpass.trim().isEmpty()) {
			errors.put("reloginpass", "确认密码不能为空！");
		} else if (!reloginpass.equals(loginpass)) {
			errors.put("reloginpass", "两次密码不一致！");
		}

		// email校验
		String email = formUser.getEmail();
		if (email == null || email.trim().isEmpty()) {
			errors.put("email", "邮箱不能为空！");
		} else if (!email.matches("^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\\.[a-zA-Z0-9_-]{2,3}){1,2})$")) {
			errors.put("email", "邮箱格式错误！");
		} else if (!userService.ajaxValidateEmail(email)) {
			errors.put("email", "邮箱已经被注册！");
		}

		// 验证码校验
		String verifyCode = formUser.getVerifyCode();
		String vCode = (String) session.getAttribute("vCode");
		if (verifyCode == null || verifyCode.trim().isEmpty()) {
			errors.put("verifyCode", "验证码不能为空！");
		} else if (!verifyCode.equalsIgnoreCase(vCode)) {
			errors.put("verifyCode", "验证码错误！");
		}

		return errors;

	}

	/**
	 * 登陆表单校验
	 * 
	 * @param formUser
	 * @param session
	 * @return
	 */
	private Map<String, String> validateLogin(User formUser, HttpSession session) {
		Map<String, String> errors = new HashMap<String, String>();

		// 用户名校验
		String loginname = formUser.getLoginname();
		if (loginname == null || loginname.trim().isEmpty()) {
			errors.put("loginname", "用户名不能为空！");
		} else if (loginname.length() < 3 || loginname.length() > 20) {
			errors.put("loginname", "用户名长度必须在3-20之间！");
		}

		// 密码校验
		String loginpass = formUser.getLoginpass();
		if (loginpass == null || loginpass.trim().isEmpty()) {
			errors.put("loginpass", "密码不能为空！");
		} else if (loginpass.length() < 3 || loginpass.length() > 20) {
			errors.put("loginpass", "密码长度必须在3-20之间！");
		}

		// 验证码校验
		String verifyCode = formUser.getVerifyCode();
		String vCode = (String) session.getAttribute("vCode");
		if (verifyCode == null || verifyCode.trim().isEmpty()) {
			errors.put("verifyCode", "验证码不能为空！");
		} else if (!verifyCode.equalsIgnoreCase(vCode)) {
			errors.put("verifyCode", "验证码错误！");
		}

		return errors;

	}

	/**
	 * 修改密码表单校验
	 * 
	 * @param formUser
	 * @param session
	 * @return
	 */
	private Map<String, String> validateUpdatePassword(User formUser, HttpSession session) {
		Map<String, String> errors = new HashMap<String, String>();

		// 原密码校验
		String loginpass = formUser.getLoginpass();
		if (loginpass == null || loginpass.trim().isEmpty()) {
			errors.put("loginpass", "密码不能为空！");
		} else if (loginpass.length() < 3 || loginpass.length() > 20) {
			errors.put("loginpass", "密码长度必须在3-20之间！");
		}
		// 新密码校验
		String newpass = formUser.getNewpass();
		if (newpass == null || newpass.trim().isEmpty()) {
			errors.put("newpass", "密码不能为空！");
		} else if (newpass.length() < 3 || newpass.length() > 20) {
			errors.put("newpass", "密码长度必须在3-20之间！");
		}
		// 确认密码校验
		String reloginpass = formUser.getReloginpass();
		if (reloginpass == null || reloginpass.trim().isEmpty()) {
			errors.put("reloginpass", "确认密码不能为空！");
		} else if (!reloginpass.equals(newpass)) {
			errors.put("reloginpass", "两次密码不一致！");
		}

		// 验证码校验
		String verifyCode = formUser.getVerifyCode();
		String vCode = (String) session.getAttribute("vCode");
		if (verifyCode == null || verifyCode.trim().isEmpty()) {
			errors.put("verifyCode", "验证码不能为空！");
		} else if (!verifyCode.equalsIgnoreCase(vCode)) {
			errors.put("verifyCode", "验证码错误！");
		}

		return errors;

	}

	/**
	 * ajax用户名是否注册校验
	 * 
	 * @param req
	 * @param resp
	 * @throws ServletException
	 * @throws IOException
	 */
	public String ajaxValidateLoginname(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String loginname = req.getParameter("loginname");
		boolean b = userService.ajaxValidateLoginname(loginname);
		resp.getWriter().print(b);
		return null;// 不转发也不重定向
	}

	/**
	 * ajax email是否注册校验
	 * 
	 * @param req
	 * @param resp
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	public String ajaxValidateEmail(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String email = req.getParameter("email");
		boolean b = userService.ajaxValidateEmail(email);
		resp.getWriter().print(b);
		return null;// 不转发也不重定向
	}

	/**
	 * ajax 验证码校验
	 * 
	 * @param req
	 * @param resp
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	public String ajaxValidateVerifyCode(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String verifyCode = req.getParameter("verifyCode");
		String vcode = (String) req.getSession().getAttribute("vCode");
		boolean b = verifyCode.equalsIgnoreCase(vcode);
		resp.getWriter().print(b);
		return null;
	}

	/**
	 * 邮件激活功能
	 * 
	 * @param req
	 * @param resp
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	public String activation(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String activationCode = req.getParameter("activationCode");

		try {
			userService.activation(activationCode);
		} catch (UserException e) {
			req.setAttribute("code", "error");
			req.setAttribute("msg", e.getMessage());
			return "f:/jsps/msg.jsp";
		}

		req.setAttribute("code", "success");
		req.setAttribute("msg", "激活成功!");

		return "f:/jsps/msg.jsp";
	}
	public String resetPassword(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String verifyCode = req.getParameter("verifyCode");
		String vcode = (String) req.getSession().getAttribute("vCode");
		boolean b = verifyCode.equalsIgnoreCase(vcode);
		resp.getWriter().print(b);
		return null;
	}
	
	/**
	 * 校验用户和邮箱是否匹配
	 * @param req
	 * @param resp
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	public String ajaxValidateLoginnameAndEmail(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		User formUser = CommonUtils.toBean(req.getParameterMap(), User.class);
		boolean b = userService.findByLoginnameAndEmail(formUser.getLoginname(),formUser.getEmail());
		resp.getWriter().print(b);
		return null;
	}
	public String sendEmailVerify(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		User formUser = CommonUtils.toBean(req.getParameterMap(), User.class);
		String emailVerify = userService.sendEmailVerify(formUser);
		resp.getWriter().print(emailVerify);
		return null;
	}
}
